import "package:get/get.dart";
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../apis/notice.dart';
import '../../../components/dialog/Dialog.dart';
import '../../../components/status/toast.dart';
import '../../../controller/gather_ctrl.dart';
import '../../../controller/network/bridge.dart';
import '../../../controller/network/network_ctrl.dart';
import '../../../controller/notice_ctrl/notice_ctrl.dart';
import '../../../model/bean/notice_bean.dart';

class NoticeMyCtrl extends GatherCtrl {
  // 查看网络状态
  final _nc = Get.find<NetworkCtrl>();

  // 选项卡（1:已读，0：未读）
  final status = 0.obs;

  // 请求参数
  final Map<String, dynamic> params = {
    "hasRead": 0,
    "page": 1,
    "rows": 10,
  }.obs;

  //申明上拉加载更多的状态
  final refreshController = RefreshController().obs;
  final flags = true.obs;

  // 组件是否初始化完成
  RxBool isInitComplete = false.obs;

  // 数据列表
  final listData = <NoticeBean>[].obs;
  final total = 0.obs;

  @override
  void onInit() {
    // 创建网络变化观察
    Bridget.createNetworkCtrl(this);

    // 读取消息列表
    readListMsg();
  }

  @override
  void onClose() {
    // 移除观察
    Bridget.delNetworkCtrl(this);
  }

  @override
  void modify() {
    // 网络恢复正常时执行当前函数
    if (_nc.networkStatus.value) readListMsg(isToast: true);
  }

  /// 读取消息列表
  /// * [isToast] bool|是否展示动画框|选填|默认值：false
  /// * [isReset] bool|是否清空数据|选填|默认值：false
  void readListMsg({bool isToast = false, bool isReset = false}) async {
    // 开启轻提示
    if (isToast) Toast.loading(title: '正在读取');

    // 获取消息列表
    NoticeListBean result = await Notice.queryListMsg(params);

    // 是否重置数据
    if (isReset) listData.clear();

    // 赋值
    if (result != null && result.list != null) {
      listData.addAll(result.list.obs);
      total.value = result.total;

      // 累加页码
      if (result.list.length > 0 && listData.value.length > 0) {
        params["page"] = params["page"] + 1;
      }

      // 没有更多数据了
      // print(listData.length >= total.value);
      if (listData.length >= total.value) {
        refreshController.value.loadNoData();
        flags.value = false;
      }
    }

    // 完成加载更多通知
    refreshController.value.loadComplete();

    // 开启轻提示
    if (isToast) Toast.closeToast();

    // 标记页面加载状态（初始化）
    if (!isInitComplete.value) isInitComplete.value = true;
  }

  /// 设置消息状态
  /// * [params] Map<String, dynamic>|请求参数|选填
  /// * [sign] int|消息列表的下标|选填
  void setNoticeStatus({Map<String, dynamic> params, int sign}) async {
    Toast.loading(title: '正在设置');

    try {
      await Notice.changeNoticeStatus(data: params);

      Toast.success(title: '设置成功');

      // 移除指定的数据
      if (sign != null) {
        listData.removeAt(sign);

        // 修改未读消息数量
        NoticeCtrl.fromJson({"messagesCount": total.value - 1});
      } else {
        listData.clear();

        // 同上
        NoticeCtrl.fromJson({"messagesCount": 0});
      }
    } catch (e) {}

    // 关闭动画
    Toast.closeToast();
  }

  /// 选项卡发送变化触发
  /// * [value] bool 被选中的选项卡对应的值|必填
  void onChangeSelectStatus(int value) {
    // 修改选中状态
    status.value = value;

    // 修改请求参数
    flags.value = true;
    params["hasRead"] = status.value;
    params["page"] = 1;

    // 读取消息列表
    readListMsg(isToast: true, isReset: true);
  }

  /// 查看未读消息
  /// * [title] String|标题|必填
  /// * [content] String|内容|必填
  /// * [id] String|消息id|选填
  /// * [sign] int|标记（下标）|选填
  void seeUnreadNotice(
    String title,
    String content, {
    String id,
    int sign,
  }) {
    Dialogs.confirmDialog(
      Get.context,
      title: title,
      content: content,
      cancelTxt: "不，留着",
      cancel: () => null,
      confirmTxt: "标记已读",
      confirm: () => setNoticeStatus(params: {"id": id}, sign: sign),
    );
  }

  /// 查看未读通知（一键设置为已读）
  void setAllReadNotice() {
    Dialogs.confirmDialog(
      Get.context,
      title: "全部已读",
      content: "是否将所有消息设置为已读？",
      cancelTxt: "放弃",
      cancel: () => null,
      confirm: () => setNoticeStatus(),
    );
  }

  /// 上拉加载更多
  void onLoading() {
    if (flags.value) {
      readListMsg();
    } else {
      refreshController.value.loadNoData();
    }
  }
}
